package com.ztewatch.wearcontacts;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Groups;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ztewatch.wearcontacts.data.ContactData;
import com.ztewatch.wearcontacts.data.EmergencyContactItem;
import com.ztewatch.wearcontacts.data.GroupItem;
import com.ztewatch.wearcontacts.loader.GroupMetaDataLoader;
import com.ztewatch.wearcontacts.service.WearContactSaveService;
import com.ztewatch.wearcontacts.utils.ContactPhotoUtils;
import com.ztewatch.wearcontacts.utils.ContactQuery;
import com.ztewatch.wearcontacts.view.EmergencyContactAdapter;
import com.ztewatch.wearcontacts.view.GroupMembershipAdapter;

public class WearContactEditActivity extends WearContactBaseActivity implements
		OnClickListener {
	private static final int LOADER_DATA = 1;
	private static final int LOADER_GROUPS = 2;
	private static final int LOADER_STARRED = 3;
	public static final int EMERGENCY_CONTACT_NUM = 6;
	private static final String STARRED_KEY_ORDER = Contacts.STARRED
			+ " COLLATE NOCASE ASC";
	public static final String SAVE_CONTACT_FLAG = "save_contact_flag";
	private Uri mLookupUri = null;
	private EditText e_name;
	private EditText e_number;
	private ImageView photo;
	private LinearLayout m_edit_photo_img_l;
	private long rowContact_id = 0;
	private Button saveMenuItem;
	private MyTextWatcher mMyTextWatcher;
	private static final int REQUESTCODE = 0;
	private int image_resid = 0;
	// group
	private Button mGroupListBtn;
	private Cursor mGroupMetaData;
	private GroupMembershipAdapter<GroupItem> mGroupAdapter;
	// private ListPopupWindow mGroupPopup;
	private long cur_group_id;
	private int cur_group_pos = 0;
	private boolean isCreateFlag = false;
	// emergency contact
	private Button mEmergencyContactBtn;
	// private ListPopupWindow mEmergencyPopup;
	private EmergencyContactAdapter mEmergencyContactAdapter;
	private Button mDelete_contact_view;
	private ArrayList<EmergencyContactItem> mEmergencyContactItems = new ArrayList<EmergencyContactItem>();
	private int cur_starred_id;
	private ArrayList<GroupItem> mGroupListItems = new ArrayList<GroupItem>();
	private boolean onlyEmergencyFlag = false;
	private boolean isVoicecall;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_edit);
		initView();
		initEmergencyData();
		initGroup();
		initActionMenu();
		isVoicecall = getIntent().getBooleanExtra(
				WearContactVoiceCallMainActivity.VOICE_CALL_FLAG, false);
	}

//	@Override
//	public void onWindowDismissed() {
//		if (saveMenuItem.isEnabled()) {
//			showOnWindosDismissedDialog();
//			return;
//		} else {
//			super.onWindowDismissed();
//		}
//	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String action = intent.getAction();
		if (WearContactBaseActivity.ACTION_SAVE_CONTACT_COMPLETED
				.equals(action)) {
			if(isVoicecall){
				Intent intent2 = new Intent(this, WearContactVoiceCallMainActivity.class);
				intent2.putExtra(SAVE_CONTACT_FLAG, true);
				startActivity(intent2);
			}else{
				Intent intent2 = new Intent(this, WearContactMainActivity.class);
				intent2.putExtra(SAVE_CONTACT_FLAG, true);
				startActivity(intent2);
			}
			finish();
		} else if (WearContactBaseActivity.ACTION_UPDATE_CONTACT_COMPLETED
				.equals(action)) {
			finish();
		} else if (WearContactBaseActivity.ACTION_EDIT_CONTACT_COMPLETED
				.equals(action)) {
			mLookupUri = intent.getData();
			if (mLookupUri != null) {
				rowContact_id = ContentUris.parseId(mLookupUri);
			}
		}
	}

	private void initGroup() {
		mGroupAdapter = new GroupMembershipAdapter<GroupItem>(
				WearContactEditActivity.this,
				R.layout.group_membership_list_item);
		String[] groupInitList = getResources().getStringArray(
				R.array.group_init_list);
		for (int i = 0; i < groupInitList.length; i++) {
			mGroupListItems.add(new GroupItem(0, groupInitList[i]));
		}
		cur_group_id = getIntent().getLongExtra(
				WearContactGroupDetailActivity.GROUP_DETAIL_ID, 0);
	}

	private void initView() {
		mMyTextWatcher = new MyTextWatcher();
		e_name = (EditText) findViewById(R.id.edit_contact_name);
		e_number = (EditText) findViewById(R.id.edit_contact_number);
		e_name.addTextChangedListener(mMyTextWatcher);
		e_number.addTextChangedListener(mMyTextWatcher);
		photo = (ImageView) findViewById(R.id.edit_photo_img);
		m_edit_photo_img_l = (LinearLayout) findViewById(R.id.edit_photo_img_l);
		m_edit_photo_img_l.setOnClickListener(this);
		photo.setOnClickListener(this);
		mGroupListBtn = (Button) findViewById(R.id.edit_group_list);
		mGroupListBtn.setOnClickListener(this);
		mEmergencyContactBtn = (Button) findViewById(R.id.edit_emergency_contact_list);
		mEmergencyContactBtn.setOnClickListener(this);
		mLookupUri = getIntent().getData();
		mDelete_contact_view = (Button) findViewById(R.id.delete_contact_btn);
		if (mLookupUri != null) {
			rowContact_id = ContentUris.parseId(mLookupUri);
			mDelete_contact_view.setVisibility(View.VISIBLE);
		} else {
			mDelete_contact_view.setVisibility(View.GONE);
		}
		mDelete_contact_view.setOnClickListener(this);
	}

	private class MyTextWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			String name = e_name.getText().toString();
			if (name != null && !TextUtils.isEmpty(name)) {
				String number = e_number.getText().toString();
				if (number != null && !TextUtils.isEmpty(number)) {
					saveMenuItem.setEnabled(true);
				} else {
					saveMenuItem.setEnabled(false);
				}
			} else {
				saveMenuItem.setEnabled(false);
			}
		}

		@Override
		public void afterTextChanged(Editable s) {

		}

	}

	private void initActionMenu() {
		saveMenuItem = (Button) findViewById(R.id.save_menu_item);
		saveMenuItem.setOnClickListener(this);
		saveMenuItem.setEnabled(false);
		View cancelMenuItem = findViewById(R.id.cancel_menu_item);
		cancelMenuItem.setOnClickListener(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		getLoaderManager().initLoader(LOADER_DATA, null, loaderCallbacks);
		getLoaderManager()
				.initLoader(LOADER_GROUPS, null, mGroupLoaderListener);
		getLoaderManager().initLoader(LOADER_STARRED, null,
				mStarredLoaderListener);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(LOADER_DATA);
		getLoaderManager().destroyLoader(LOADER_GROUPS);
	}

	private void setDataToView(Cursor cursor) {
		rowContact_id = cursor.getInt(ContactQuery.RAW_CONTACT_ID);

		String number_type = cursor.getString(ContactQuery.DATA2);
		String mimeType = cursor.getString(ContactQuery.MIMETYPE);
		int starred = cursor.getInt(ContactQuery.STARRED);

		if (number_type != null
				&& number_type.equals(String.valueOf(Phone.TYPE_MOBILE))) {
			String display_name = cursor.getString(ContactQuery.DISPLAY_NAME);
			String number = cursor.getString(ContactQuery.DATA1);
			e_name.setText(display_name);
			e_number.setText(number);
		}
		if (starred != 0) {
			mEmergencyContactBtn.setText(getResources().getString(
					R.string.edit_contact_emergency_contact_num, starred));
			cur_starred_id = starred;
		} else {
			mEmergencyContactBtn.setText(getResources().getString(
					R.string.edit_contact_emergency_contact_hint));
			cur_starred_id = 0;
		}
		if (GroupMembership.CONTENT_ITEM_TYPE.equals(mimeType)) {
			String group_id = cursor.getString(ContactQuery.DATA1);
			cur_group_id = Long.valueOf(group_id);
			if (mGroupAdapter != null && !TextUtils.isEmpty(group_id)) {
				for (int i = 0; i < mGroupAdapter.getCount(); i++) {
					GroupItem groupItem = mGroupAdapter.getItem(i);
					if (group_id
							.equals(String.valueOf(groupItem.getGroup_id()))) {
						mGroupListBtn.setText(groupItem.getGroup_title());
						break;
					}
				}
			}
		}

		byte[] str = cursor.getBlob(ContactQuery.DATA15);

		if (str != null && image_resid == 0) {
			// InputStream inputStream = new ByteArrayInputStream(str);
			// Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			final Bitmap bitmap = BitmapFactory.decodeByteArray(str, 0,
					str.length);
			photo.setImageBitmap(bitmap);
		}else{
			photo.setImageResource(R.drawable.ic_address_portrait);
		}
	}

	private final LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
			// mCursorAdapter.swapCursor(arg1);
			if (cursor != null) {
				if (!cursor.moveToFirst()) {
					cursor.close();
				} else {
					do {
						setDataToView(cursor);
					} while (cursor.moveToNext());
				}
			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			if (mLookupUri != null) {
				Uri uri = Uri.withAppendedPath(mLookupUri,
						Contacts.Entity.CONTENT_DIRECTORY);
				return new CursorLoader(WearContactEditActivity.this, uri,
						ContactQuery.COLUMNS, null, null,
						Contacts.Entity.RAW_CONTACT_ID);
			} else {
				if (image_resid == 0) {
//					photo.setImageBitmap(Bytes2Bimap(getDefaultPhotoArray()));
					photo.setImageResource(R.drawable.ic_address_portrait);
				}
				return null;
			}

		}
	};

	/**
	 * The listener for the group meta data loader for all groups.
	 */
	private final LoaderManager.LoaderCallbacks<Cursor> mGroupLoaderListener = new LoaderCallbacks<Cursor>() {

		@Override
		public CursorLoader onCreateLoader(int id, Bundle args) {
			return new GroupMetaDataLoader(WearContactEditActivity.this,
					Groups.CONTENT_URI);
		}

		@Override
		public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
			initGroupList(data);
		}

		@Override
		public void onLoaderReset(Loader<Cursor> loader) {
		}
	};

	private final LoaderManager.LoaderCallbacks<Cursor> mStarredLoaderListener = new LoaderCallbacks<Cursor>() {

		@Override
		public CursorLoader onCreateLoader(int id, Bundle args) {
			return new CursorLoader(WearContactEditActivity.this,
					Contacts.CONTENT_URI, ContactQuery.CONTACT_PROJECTION,
					Contacts.STARRED + "!=?", new String[] { "0" },
					STARRED_KEY_ORDER);
		}

		@Override
		public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
			// Toast.makeText(WearContactEditActivity.this,
			// "starred count = " + c.getCount(), Toast.LENGTH_LONG)
			// .show();
			initEmergenContactItems();
			c.moveToPosition(-1);
			int emergencyCount = 0;
			while (c.moveToNext()) {
				long contactId = c.getLong(ContactQuery.CONTACT__ID);
				int starredId = c.getInt(ContactQuery.CONTACT_STARRED);
				String contactName = c
						.getString(ContactQuery.CONTACT_DISPLAY_NAME);
				String lookupkey = c.getString(ContactQuery.CONTACT_LOOKUP_KEY);
				if (starredId != 0) {
					EmergencyContactItem mEmergencyContactItem = mEmergencyContactItems
							.get(starredId);
					mEmergencyContactItem.setmContactId(contactId);
					mEmergencyContactItem.setmStarred(starredId);
					mEmergencyContactItem.setmName(contactName);
					mEmergencyContactItem.setmLookUpKey(lookupkey);
					emergencyCount++;
				}
			}
			if (emergencyCount == 1) {
				for (int i = 0; i < mEmergencyContactItems.size(); i++) {
					EmergencyContactItem mEmergencyContactItem = mEmergencyContactItems
							.get(i);
					if (rowContact_id != 0
							&& mEmergencyContactItem.getmContactId() == rowContact_id) {
						onlyEmergencyFlag = true;
					}
				}
			} else {
				onlyEmergencyFlag = false;
			}

		}

		@Override
		public void onLoaderReset(Loader<Cursor> loader) {
		}
	};

	private byte[] getDefaultPhotoArray() {
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_address_portrait);
		ByteArrayOutputStream array = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, array);
		return array.toByteArray();
	}

	protected void initEmergenContactItems() {
		for (int i = 0; i < mEmergencyContactItems.size(); i++) {
			EmergencyContactItem mEmergencyContactItem = mEmergencyContactItems
					.get(i);
			mEmergencyContactItem.setmContactId(0);
			mEmergencyContactItem.setmStarred(0);
			mEmergencyContactItem.setmName(null);
			if (i == 0) {
				mEmergencyContactItem.setmName(getResources().getString(
						R.string.edit_contact_emergency_contact_hint));
			}
		}
	}

	private Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

	private byte[] getPhotoArray(int resid) {
		if (resid == 0) {
			return getDefaultPhotoArray();
		}
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resid);
		ByteArrayOutputStream array = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, array);
		return array.toByteArray();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.save_menu_item:
			String name = e_name.getText().toString();
			String number = e_number.getText().toString();

			if (rowContact_id != 0) {
				updateContact(name, number);
			} else {
				saveContacat(name, number,
						WearContactBaseActivity.ACTION_SAVE_CONTACT_COMPLETED);
			}
			break;
		case R.id.cancel_menu_item:
			if (saveMenuItem.isEnabled()) {
				showOnWindosDismissedDialog();
			} else {
				finish();
			}
			break;
		case R.id.edit_photo_img:
		case R.id.edit_photo_img_l:
			Intent intent = new Intent();
			intent.setClass(this, WearContactSelImgActivity.class);
			startActivityForResult(intent, REQUESTCODE);
			break;
		case R.id.edit_group_list:
			onClickGroupList();
			break;
		case R.id.edit_emergency_contact_list:
			onClickEmergencyContact();
			break;
		case R.id.delete_contact_btn:
			if (onlyEmergencyFlag) {
				showDeleteEmergencyContactDialog();
			} else {
				showDeleteContactDialog();
			}
			break;
		default:
			break;
		}
	}

	private void showDeleteContactDialog() {
		AlertDialog.Builder builder = new Builder(this,
				R.style.WatchDialogTheme);
		View view = getLayoutInflater().inflate(R.layout.dialog_view, null);
		// TextView title = (TextView) view.findViewById(R.id.dialog_title);
		TextView msg = (TextView) view.findViewById(R.id.dialog_msg);
		Button cancel_btn = (Button) view.findViewById(R.id.dialog_cancel);
		Button ok_btn = (Button) view.findViewById(R.id.dialog_ok);
		msg.setText(R.string.delete_contact_msg);
		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		setDialogBottomShow(alertDialog);
		cancel_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// if (onlyEmergencyFlag) {
				// showDeleteEmergencyContactDialog();
				// } else {
				deleteContact();
				// }
				alertDialog.dismiss();
			}
		});
		alertDialog.show();
	}

	private void showDeleteEmergencyContactDialog() {
		AlertDialog.Builder builder = new Builder(this,
				R.style.WatchDialogTheme);
		View view = getLayoutInflater().inflate(R.layout.dialog_sample_view,
				null);
		// TextView title = (TextView) view.findViewById(R.id.dialog_title);
		TextView msg = (TextView) view.findViewById(R.id.dialog_msg);
		// Button cancel_btn = (Button) view.findViewById(R.id.dialog_cancel);
		Button ok_btn = (Button) view.findViewById(R.id.dialog_ok);
		msg.setText(R.string.delete_only_contact_emergency_msg);
		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		setDialogBottomShow(alertDialog);
		// cancel_btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// alertDialog.dismiss();
		// }
		// });
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// deleteContact();
				alertDialog.dismiss();
			}
		});
		alertDialog.show();
	}

	private void showOnWindosDismissedDialog() {
		AlertDialog.Builder builder = new Builder(this,
				R.style.WatchDialogTheme);
		View view = getLayoutInflater().inflate(R.layout.dialog_view, null);
		// TextView title = (TextView) view.findViewById(R.id.dialog_title);
		TextView msg = (TextView) view.findViewById(R.id.dialog_msg);
		Button cancel_btn = (Button) view.findViewById(R.id.dialog_cancel);
		Button ok_btn = (Button) view.findViewById(R.id.dialog_ok);
		msg.setText(R.string.edit_contact_swiperight_warning);
		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		setDialogBottomShow(alertDialog);

		cancel_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
				finish();
			}
		});
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String name = e_name.getText().toString();
				String number = e_number.getText().toString();
				if (rowContact_id != 0) {
					updateContact(name, number);
				} else {
					saveContacat(
							name,
							number,
							WearContactBaseActivity.ACTION_SAVE_CONTACT_COMPLETED);
				}
				alertDialog.dismiss();
				finish();
			}
		});
		alertDialog.show();
	}

	private void setDialogBottomShow(final AlertDialog alertDialog) {
		Window window = alertDialog.getWindow();
		WindowManager.LayoutParams wmlp = window.getAttributes();
		wmlp.gravity = Gravity.BOTTOM;
		window.setAttributes(wmlp);
		alertDialog.setCancelable(false);
	}

	private void deleteContact() {
		Intent saveIntent = null;
		saveIntent = WearContactSaveService.createDeleteContactIntent(this,
				mLookupUri, this.getClass(),
				WearContactBaseActivity.ACTION_DELETE_CONTACT_COMPLETED);
		startService(saveIntent);
		boolean isEditMainActivityFlag = getIntent().getBooleanExtra(
				WearContactEditMainActivity.EDIT_MAIN_ACTIVITY_FALG, false);

		Intent intent = new Intent();
		if (isEditMainActivityFlag) {
			intent.setClass(this, WearContactEditMainActivity.class);
		} else {
			intent.setClass(this, WearContactMainActivity.class);
		}
		startActivity(intent);
		finish();
	}

	private void initEmergencyData() {
		for (int i = 0; i < EMERGENCY_CONTACT_NUM; i++) {
			EmergencyContactItem mEmergencyContactItem = new EmergencyContactItem();
			mEmergencyContactItems.add(mEmergencyContactItem);
		}
	}

	private void onClickEmergencyContact() {
		mEmergencyContactAdapter = new EmergencyContactAdapter(this,
				mEmergencyContactItems);
		// mEmergencyPopup = new ListPopupWindow(this, null);
		// mEmergencyPopup.setAnchorView(mEmergencyContactBtn);
		// mEmergencyPopup.setAdapter(mEmergencyContactAdapter);
		// mEmergencyPopup.setModal(true);
		// mEmergencyPopup
		// .setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
		// mEmergencyPopup.show();
		// ListView listView = mEmergencyPopup.getListView();
		// listView.setOverScrollMode(0);
		// TextView textView = new TextView(this);
		// textView.setText(getResources().getString(
		// R.string.edit_contact_emergency_contact_hint));
		// listView.addHeaderView(textView);// add not set
		// listView.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// final int position, long id) {
		// mEmergencyPopup.dismiss();
		// emergencyListContactOnClickItem(position);
		// }
		// });

		AlertDialog.Builder builder = new Builder(WearContactEditActivity.this);
		View view = getLayoutInflater().inflate(R.layout.dialog_listview, null);
		ListView dialog_listView = (ListView) view
				.findViewById(R.id.dialog_listview);

		mEmergencyContactAdapter.setCurPosition(cur_starred_id);

		dialog_listView.setAdapter(mEmergencyContactAdapter);

		// TextView textView = new TextView(this);
		// textView.setText(getResources().getString(
		// R.string.edit_contact_emergency_contact_hint));
		// dialog_listView.addHeaderView(textView);// add not set

		dialog_listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		dialog_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				emergencyListContactOnClickItem(position);
				alertDialog.dismiss();
			}
		});
		alertDialog.show();
	}

	private void onClickGroupList() {
		if (mGroupMetaData != null && mGroupAdapter != null) {
			// mGroupMetaData.moveToPosition(-1);
			// while (mGroupMetaData.moveToNext()) {
			// long groupId = mGroupMetaData
			// .getLong(GroupMetaDataLoader.GROUP_ID);
			// String title = mGroupMetaData
			// .getString(GroupMetaDataLoader.TITLE);
			// mGroupAdapter.add(new GroupItem(groupId, title));
			// }
			// int group_index = 0;
			// int i = 0;
			// for (i = 0; i < mGroupAdapter.getCount(); i++) {
			// GroupItem groupItem = mGroupAdapter.getItem(i);
			// if (cur_group_id != 0
			// && cur_group_id == groupItem.getGroup_id()) {
			// group_index = i;
			// break;
			// }
			// }
			mGroupAdapter.setCurPosition(cur_group_pos);

			AlertDialog.Builder builder = new Builder(
					WearContactEditActivity.this);
			View view = getLayoutInflater().inflate(R.layout.dialog_listview,
					null);
			ListView dialog_listView = (ListView) view
					.findViewById(R.id.dialog_listview);
			dialog_listView.setAdapter(mGroupAdapter);
			dialog_listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			// dialog_listView.setSelected(true);

			// dialog_listView.setSelection(group_index);
			builder.setView(view);
			final AlertDialog alertDialog = builder.create();
			dialog_listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					GroupItem item = mGroupAdapter.getItem(position);
					long groupId = item.getGroup_id();
					String title = item.getGroup_title();
					mGroupListBtn.setText(title);
					cur_group_id = groupId;
					if (position != 0 && groupId == 0) {
						isCreateFlag = true;
					}
					cur_group_pos = position;
					alertDialog.dismiss();
				}
			});
			alertDialog.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUESTCODE && resultCode == RESULT_OK) {
			if (data != null) {
				Bundle data1 = data.getExtras();
				int index = data1.getInt(WearContactSelImgActivity.IMAGE_INDEX);
				image_resid = WearContactSelImgActivity.imageIds[index];
				photo.setImageBitmap(Bytes2Bimap(getPhotoArray(image_resid)));
			}
		}
	}

	private boolean saveContacat(String name, String phone,
			String callbackAction) {
		// Uri photoUri = null;
		Intent saveIntent = null;
		ContactData contactData = new ContactData();
		contactData.setName(name);
		contactData.setPhone(phone);
		contactData.setGroup_id(cur_group_id);
		contactData.setStarred_id(cur_starred_id);
		contactData.setCreateGroup_flag(isCreateFlag);
		contactData.setGroup_title(mGroupListBtn.getText().toString());

		if (image_resid != 0) {
			// photoUri = ContactPhotoUtils.getResourceUri(image_resid,
			// getPackageName());
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					image_resid);
			byte[] photo = ContactPhotoUtils.compressBitmap(bmp);
			contactData.setPhoto(photo);
		} else {
			// photoUri = ContactPhotoUtils
			// .getResourceUri(R.drawable.zte_contact_picture_holo_light,
			// getPackageName());
			contactData.setPhoto(null);
		}
		saveIntent = WearContactSaveService.createSaveContactIntent(this,
				contactData, this.getClass(), callbackAction);
		// Intent saveIntent = WearContactSaveService.createSaveContactIntent(
		// this, name, phone, cur_group_id, cur_starred_id, photoUri);
		startService(saveIntent);
		return true;
	}

	private boolean updateContact(String name, String phone) {
		Intent saveIntent = null;
		ContactData contactData = new ContactData();
		contactData.setName(name);
		contactData.setPhone(phone);
		contactData.setGroup_id(cur_group_id);
		contactData.setStarred_id(cur_starred_id);
		contactData.setCreateGroup_flag(isCreateFlag);
		contactData.setGroup_title(mGroupListBtn.getText().toString());
		contactData.setRaw_contact_id(rowContact_id);
		// Uri photoUri = null;
		if (image_resid != 0) {
			// photoUri = ContactPhotoUtils.getResourceUri(image_resid,
			// getPackageName());
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					image_resid);
			byte[] photo = ContactPhotoUtils.compressBitmap(bmp);
			contactData.setPhoto(photo);
		} else {
			// photoUri = ContactPhotoUtils
			// .getResourceUri(R.drawable.zte_contact_picture_holo_light,
			// getPackageName());
			contactData.setPhoto(null);
		}
		saveIntent = WearContactSaveService.createUpdateContactIntent(this,
				contactData, this.getClass(),
				WearContactBaseActivity.ACTION_UPDATE_CONTACT_COMPLETED);
		// saveIntent = WearContactSaveService.createUpdateContactIntent(this,
		// rowContact_id, name, phone, cur_group_id, photoUri);
		startService(saveIntent);
		return true;
	}

	private void saveCurContactStarred(int position) {
		if (mLookupUri != null) {
			Intent saveIntent = null;
			saveIntent = WearContactSaveService.createSetStarredIntent(
					WearContactEditActivity.this, mLookupUri, position);
			startService(saveIntent);
		}
	}

	private void saveSelectContactStarred(
			EmergencyContactItem mEmergencyContactItem) {
		long contactId = mEmergencyContactItem.getmContactId();
		String lookupKey = mEmergencyContactItem.getmLookUpKey();
		Uri uri = Contacts.getLookupUri(contactId, lookupKey);
		if (uri != null) {
			Intent saveIntent = null;
			saveIntent = WearContactSaveService.createSetStarredIntent(
					WearContactEditActivity.this, uri, 0);
			startService(saveIntent);
		}
	}

	private void showChangeStarredDialog(final int position,
			final EmergencyContactItem mEmergencyContactItem) {
		AlertDialog.Builder builder = new Builder(WearContactEditActivity.this);
		View view = getLayoutInflater().inflate(R.layout.dialog_view, null);
		// TextView title = (TextView) view.findViewById(R.id.dialog_title);
		TextView msg = (TextView) view.findViewById(R.id.dialog_msg);
		Button cancel_btn = (Button) view.findViewById(R.id.dialog_cancel);
		Button ok_btn = (Button) view.findViewById(R.id.dialog_ok);
		msg.setText(getResources().getString(
				R.string.emergency_contact_change_msg,
				mEmergencyContactItem.getmStarred()));
		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		setDialogBottomShow(alertDialog);
		cancel_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String name = e_name.getText().toString();
				String number = e_number.getText().toString();
				if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(number)) {
					saveSelectContactStarred(mEmergencyContactItem);
					saveCurContactStarred(position);
					if (mLookupUri == null) {
						cur_starred_id = mEmergencyContactItem.getmStarred();
						mEmergencyContactBtn.setText(getResources().getString(
								R.string.edit_contact_emergency_contact_num,
								cur_starred_id));
						saveContacat(
								name,
								number,
								WearContactBaseActivity.ACTION_EDIT_CONTACT_COMPLETED);
					}
				} else {
					Toast.makeText(
							WearContactEditActivity.this,
							getResources().getString(
									R.string.save_contact_name_number_msg),
							Toast.LENGTH_LONG).show();
				}
				alertDialog.dismiss();
			}
		});
		alertDialog.show();
	}

	private void showChangeOnlyEmergencyStarredDialog(final int position) {
		AlertDialog.Builder builder = new Builder(WearContactEditActivity.this);
		View view = getLayoutInflater().inflate(R.layout.dialog_sample_view,
				null);
		// TextView title = (TextView) view.findViewById(R.id.dialog_title);
		TextView msg = (TextView) view.findViewById(R.id.dialog_msg);
		// Button cancel_btn = (Button) view.findViewById(R.id.dialog_cancel);
		Button ok_btn = (Button) view.findViewById(R.id.dialog_ok);
		msg.setText(R.string.edit_only_contact_emergency_msg);
		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		setDialogBottomShow(alertDialog);
		// cancel_btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// alertDialog.dismiss();
		// }
		// });
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// saveCurContactStarred(position);
				alertDialog.dismiss();
			}
		});
		alertDialog.show();
	}

	private void initGroupList(Cursor data) {
		mGroupMetaData = data;
		mGroupMetaData.moveToPosition(-1);
		mGroupAdapter.clear();

		for (int i = 0; i < mGroupListItems.size(); i++) {
			mGroupAdapter.add(mGroupListItems.get(i));
		}
		while (mGroupMetaData.moveToNext()) {
			long groupId = mGroupMetaData.getLong(GroupMetaDataLoader.GROUP_ID);
			String title = mGroupMetaData.getString(GroupMetaDataLoader.TITLE);
			boolean isExist = false;
			for (int i = 0; i < mGroupAdapter.getCount(); i++) {
				if (mGroupAdapter.getItem(i).getGroup_title().equals(title)) {
					mGroupAdapter.getItem(i).setGroup_id(groupId);
					isExist = true;
					break;
				}
			}
			if (!isExist) {
				mGroupAdapter.add(new GroupItem(groupId, title));
			}
			if (cur_group_id != 0 && groupId == cur_group_id) {
				mGroupListBtn.setText(title);
			}
		}
		int i = 0;
		for (i = 0; i < mGroupAdapter.getCount(); i++) {
			GroupItem groupItem = mGroupAdapter.getItem(i);
			if (cur_group_id != 0 && cur_group_id == groupItem.getGroup_id()) {
				cur_group_pos = i;
				break;
			}
		}
	}

	private void emergencyListContactOnClickItem(final int position) {
		if (mLookupUri != null) {// edit
			if (position == 0) {
				// do not set
				if (cur_starred_id != 0) {
					if (onlyEmergencyFlag) {
						showChangeOnlyEmergencyStarredDialog(position);
					} else {
						saveCurContactStarred(position);
					}
				}
			} else {
				final EmergencyContactItem mEmergencyContactItem = mEmergencyContactItems
						.get(position);
				if (mEmergencyContactItem.getmStarred() != 0
						&& mEmergencyContactItem.getmStarred() != cur_starred_id) {
					// do have emergency contact
					showChangeStarredDialog(position, mEmergencyContactItem);
				} else {
					saveCurContactStarred(position);
				}
			}
		} else {// new
			if (position == 0) {
				mEmergencyContactBtn.setText(getResources().getString(
						R.string.edit_contact_emergency_contact_hint));
				cur_starred_id = 0;
			} else {
				final EmergencyContactItem mEmergencyContactItem = mEmergencyContactItems
						.get(position);
				if (mEmergencyContactItem.getmStarred() != 0) {
					showChangeStarredDialog(position, mEmergencyContactItem);
				} else {
					cur_starred_id = position;
					mEmergencyContactBtn.setText(getResources().getString(
							R.string.edit_contact_emergency_contact_num,
							cur_starred_id));
				}
			}
		}
	}
}
